import { findArticleListByLabel, getHotArticleLabelList } from '@/services/articles';
import { findTodayHaveSing, getSignInDay, signIn } from '@/services/user';
import useRequest from '@ahooksjs/use-request';
import { EyeOutlined, LikeOutlined, MessageOutlined, UserOutlined } from '@ant-design/icons';
import { Avatar, Button, Divider, List, message, Skeleton, Tabs, Tag, Typography } from 'antd';
import classNames from 'classnames';
import dayjs from 'dayjs';
import { useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import styles from './index.less';

const { Paragraph } = Typography;

type Props = {};
const Index: React.FC<Props> = () => {
  const [hotArticleLabelList, setHotArticleLabelList] = useState<
    (ARTICLEAPI.ArticleLabe & { isActivate?: boolean })[]
  >([]);
  const [signInToday, setSignInToday] = useState<number>(0);
  const [signInDays, setSignInDays] = useState<number>(0);
  const [articleList, setArticleList] = useState<ARTICLEAPI.ARTICLE[]>();
  // 根据标签获取文章
  const { run: findArticleListByLabelRun, loading } = useRequest(findArticleListByLabel, {
    manual: true,
    onSuccess(res) {
      const {
        code,
        data: { records = [] },
        message: msg,
      } = res;
      if (code === 200) {
        setArticleList(records);
      } else {
        message.error(msg);
      }
    },
  });
  useRequest(getHotArticleLabelList, {
    onSuccess(res) {
      const {
        data: { records = [] },
        code,
        message: msg,
      } = res;
      if (code === 200) {
        if (records.length > 0) {
          records[0].isActivate = true;
          findArticleListByLabelRun({
            pageSize: 10,
            current: 1,
            articleLabelId: records[0].articleLabelId,
          });
        }
        setHotArticleLabelList(records);
      } else {
        message.error(msg);
      }
    },
  });
  // 获取签到天数
  const { run: findTodayHaveSingRun } = useRequest(findTodayHaveSing, {
    onSuccess(res) {
      const { code, message: msg, data = 0 } = res;
      console.log(data);

      if (code === 200) {
        setSignInToday(data);
      } else {
        message.error(msg);
      }
    },
  });

  // 获取连续签到天数
  const { run: getSignInDayRun } = useRequest(getSignInDay, {
    onSuccess(res) {
      const { code, message: msg, data } = res;
      if (code === 200) {
        setSignInDays(data);
      } else {
        message.error(msg);
      }
    },
  });

  // 签到
  const { run: signInRun, loading: signInLoading } = useRequest(signIn, {
    manual: true,
    onSuccess(res) {
      const { code, message: msg } = res;
      if (code === 200) {
        message.success('签到成功');
        findTodayHaveSingRun();
        getSignInDayRun();
      } else {
        message.error(msg);
      }
    },
  });

  // 标签改变
  const tabChangeHandler = (e: string) => {
    console.log(e);
  };

  // 文章列表
  const recommendContent = () => {
    return (
      <div className={styles.content}>
        {!loading && articleList ? (
          <List
            itemLayout="horizontal"
            dataSource={articleList}
            renderItem={(item) => (
              <li
                className={styles.articleItem}
                onClick={() => window.open(`/article/view/${item.articleId}`)}
              >
                <div className={styles.metaContainer}>
                  <div className={styles.headPortrait}>
                    <Avatar size={24} icon={<UserOutlined />} src={item.user.headPortrait} />
                  </div>
                  <div>{item.user.nickname}</div>
                  <div>{dayjs(item.articleAmendTime).fromNow()}</div>
                  <div>
                    {item.articleLabelList?.map((subItem) => {
                      return <Tag key={subItem.articleLabelId}>{subItem.articleLabelName}</Tag>;
                    })}
                  </div>
                </div>
                <div className={styles.mainWrapper}>
                  <div className={styles.left}>
                    <div className={styles.articleTitle}>{item.articleTitle}</div>
                    <Paragraph ellipsis={{ rows: 2, expandable: false }}>
                      {item.articleSummary}
                    </Paragraph>
                    <div className={styles.actions}>
                      <div className={styles.actionIcon} key="1">
                        <EyeOutlined />
                        <span>{item.articleInteraction.articleLookCount}</span>
                      </div>
                      <div className={styles.actionIcon} key="2">
                        <LikeOutlined />
                        <span>{item.articleInteraction.articleLikeCount}</span>
                      </div>
                      <div className={styles.actionIcon} key="3">
                        <MessageOutlined />
                        <span>{item.articleInteraction.articleCommentCount}</span>
                      </div>
                    </div>
                  </div>
                  {item.articleCover && (
                    <div className={styles.articleCover}>
                      <img src={item.articleCover} alt="" />
                    </div>
                  )}
                </div>
              </li>
            )}
          />
        ) : (
          <Skeleton className={styles.articleItem} />
        )}
      </div>
    );
  };
  // 加载更多文章
  const loadMoreData = () => {};

  // 激活标签
  const labelActivate = (id: number) => {
    const newGotArticleLabelList = hotArticleLabelList.map((item) => {
      if (item.articleLabelId === id) {
        item.isActivate = true;
      } else {
        item.isActivate = false;
      }
      return item;
    });
    setHotArticleLabelList(newGotArticleLabelList);
    findArticleListByLabelRun({
      pageSize: 10,
      current: 1,
      articleLabelId: id,
    });
  };
  return (
    <div className={styles.plazaWrapper}>
      <div className={styles.left}>
        <div className={styles.labelList}>
          {hotArticleLabelList.length > 0 ? (
            hotArticleLabelList.map((item) => {
              return (
                <div
                  onClick={() => labelActivate(item.articleLabelId)}
                  className={classNames(
                    styles.labelItem,
                    item?.isActivate ? styles.labelItemActivate : null,
                  )}
                  key={item.articleLabelId}
                >
                  {item.articleLabelName}
                </div>
              );
            })
          ) : (
            <Skeleton active />
          )}
        </div>
      </div>
      <div className={styles.middle}>
        <InfiniteScroll
          style={{ width: '100%' }}
          dataLength={hotArticleLabelList.length}
          next={loadMoreData}
          hasMore={hotArticleLabelList.length < 3}
          loader={() => (
            <div>
              {!loading && articleList ? (
                <Skeleton style={{ backgroundColor: '#fff' }} active />
              ) : null}
            </div>
          )}
          endMessage={<Divider plain>没有更多了,快去创作吧!</Divider>}
          scrollableTarget="scrollableDiv"
        >
          <div className={styles.middleTopTab}>
            <Tabs
              defaultActiveKey="1"
              onChange={tabChangeHandler}
              items={[
                {
                  label: `推荐`,
                  key: '1',
                  children: recommendContent(),
                },
                {
                  label: `最新`,
                  key: '2',
                  children: recommendContent(),
                },
              ]}
            />
          </div>
        </InfiniteScroll>
      </div>
      <div className={styles.right}>
        <div className={styles.signWrapper}>
          <div className={styles.signLeft}>
            <div className={styles.signTitle}>
              {signInDays > 0 ? (
                <>
                  连续签到
                  <span>{signInToday}天</span>
                </>
              ) : (
                <div>今天还没有签到</div>
              )}
            </div>
            <div className={styles.signSubTitle}>连续签到有好礼</div>
          </div>
          <Button
            disabled={signInDays > 0}
            type="primary"
            onClick={signInRun}
            loading={signInLoading}
          >
            签到
          </Button>
        </div>
      </div>
    </div>
  );
};
export default Index;
